<?php

declare(strict_types=1);

namespace LnkAdmin\controller\auth;

use LnkAdmin\controller\Backend;
use LnkAdmin\model\auth\AdminModel;
use LnkAdmin\model\auth\DeptModel;
use app\Request;
use LnkAdmin\controller\traits\Crud;
use think\facade\Db;
use think\Response;

class Dept extends Backend
{
    use Crud;

    public function initialize()
    {
        $this->model = new DeptModel();
    }


    /**
     * 查看
     *
     * @return Response
     */
    public function index(Request $request): Response
    {
        $list = $this->model->select();               // 查询全部
        $list = list_to_tree($list);
        return success('获取成功', $list);
    }


    /**
     * 删除(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $pk = $this->model->getPk();
        // 判断是否有下级
        $isChild = $this->model->where('parent_id',$id)->count() > 0 ? true:false;
        if($isChild){
            return error('删除失败,该部门有下级');
        }
        $result = Db::transaction(function () use ($id, $pk) {
            $count = 0;
            foreach ($this->model->whereIn($pk, $id)->cursor() as $row) {
                $count += $row->delete();
            }
            return $count;
        });
        if ($result) {
            return success('删除成功', $result);
        }
        return error('删除失败');
    }



}